package cc.laop.ftp;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.io.File;
import java.io.IOException;

/**
 * @Auther: Pengpeng
 * @Date: create in 2018/1/1 20:00
 * @Description:
 */
public class FtpUpload {

    public static void main(String[] args) throws IOException, JSchException, SftpException {
        System.out.println("==== start ====");
        FtpUtils.initChannel();
        File file = new File(rootpath);
        pathLoop(file);
        FileUpdateCheck.serialize();
        FtpUtils.close();
        System.out.println("==== end ====");
    }


    private static void pathLoop(File file) throws IOException, SftpException {
        String filename = file.getName();
        for (String exc : exclude) {
            if (filename.equals(exc)) {
                return;
            }
        }

        if (file.isDirectory()) {
            mkdir(file);
            File[] files = file.listFiles();
            for (File f : files) {
                pathLoop(f);
            }
        } else {
            upload(file);
        }
    }

    public static void mkdir(File file) {
        String filepath = file.getAbsolutePath();
        filepath = rwpath(filepath);
        try {
            FtpUtils.mkdir(filepath);
        } catch (SftpException e) {
            System.out.println("------ mkdir failed: " + filepath);
        }
    }


    private static void upload(File file) throws IOException, SftpException {
        String filepath = file.getAbsolutePath();
        String ftpath = rwpath(filepath);
        if (FileUpdateCheck.check(filepath)) {
            System.out.println(ftpath);
            FtpUtils.upload(filepath, ftpath);
        }
    }


    private static String rwpath(String path) {
        path = path.substring(rootpath.length()).replace("\\", "/");
        //path = path.substring(0, path.lastIndexOf("/"));
        path = topath + path;
        return path;
    }


    //private static String rootpath = "F:\\Project\\aiSys";
    //private static String topath = "/home/childe/mygit/laopSys";
    private static String rootpath = "F:\\Project\\mygit\\laopLearn";
    private static String topath = "/home/childe/mygit/laopLean";

    private static String[] exclude = new String[]{"target", ".svn", "RemoteSystemsTempFiles", ".metadata", "" +
            ".recommenders", "Servers", ".git", "node_modules", ".idea", ".settings", ".project", ".jupiter", "" +
            ".classpath", "logs", "out"};
}
